package com.spark.lola.controller.sup;


import com.alibaba.fastjson.JSON;
import com.spark.lola.constant.SupOrderAction;
import com.spark.lola.entity.pur.OrderLocation;
import com.spark.lola.logistics.mapper.LocationInfoMapper;
import com.spark.lola.support.ai.service.LicensePlateService;
import com.spark.lola.support.core.entity.KafkaMessage;
import com.spark.lola.support.mybatis.common.QueryCondition;
import com.spark.lola.support.wms.configuration.WmsProperties;
import com.spark.lola.support.wms.constant.KafkaTopic;
import com.spark.lola.support.wms.request.OrderActionRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import com.spark.lola.support.mybatis.controller.BaseController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spark.lola.entity.pur.OrderInfo;
import com.spark.lola.mapper.pur.OrderInfoMapper;
import com.spark.lola.service.pur.IOrderInfoService;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.mybatis.entity.PageParam;
import com.spark.lola.support.mybatis.entity.QueryParam;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dengyejun
 * @since 2020-04-24
 */
@RestController
@RequestMapping("/api/pur/order-info")
public class OrderInfoController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(OrderInfoController.class);
    @Autowired
    private OrderInfoMapper currentMapper;
    @Autowired
    private IOrderInfoService currentService;
    @Autowired
    private WmsProperties wmsProperties;
    @Autowired
    private LicensePlateService licensePlateService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private LocationInfoMapper locationInfoMapper;

    @RequiresPermissions(value = "m5250")
    @RequestMapping(value = "/findBy", consumes = "application/json")
    public ResponseBean findBy(@RequestBody QueryParam<OrderInfo> queryBean,
                               @SessionAttribute ShiroUser shiroUser) {
        // 是否业务员
        if(wmsProperties.getPurchase().getDutyId().get(1).equals(shiroUser.getDutyId())) {
            bindSelfQuery(queryBean,"o.salesmanId",shiroUser);
        }
        // 是否接货员
        if(wmsProperties.getPurchase().getDutyId().get(2).equals(shiroUser.getDutyId())) {
            bindSelfQuery(queryBean,"o.consigneeId",shiroUser);
        }
        // 当前管理员是否 出纳岗位
        if(wmsProperties.getPurchase().getDutyId().get(4).equals(shiroUser.getDutyId())){
            bindSelfQuery(queryBean,"o.cashierId",shiroUser);
        }
        // 当前管理员是否 业务主管岗位
        if(wmsProperties.getPurchase().getDutyId().get(0).equals(shiroUser.getDutyId())){
            List<Long> loactionIds = locationInfoMapper.getIdsByLeaderId(shiroUser.getId());
            if( loactionIds.size()==0) {
                // 强制过滤
                loactionIds.add(0L);
            }
            String ids = StringUtils.join(loactionIds.toArray(),",");
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setKey("o.destinationId");
            queryCondition.setOper("in");
            queryCondition.setValue(ids);
            queryBean.getQueryList().add(queryCondition);
        }

        // 当前管理员是否 财务岗位
        if(wmsProperties.getPurchase().getDutyId().get(3).equals(shiroUser.getDutyId())){
            List<Long> loactionIds = locationInfoMapper.getIdsByPurchaseId(shiroUser.getId());
            if( loactionIds.size()==0) {
                // 强制过滤
                loactionIds.add(0L);
            }
            String ids = StringUtils.join(loactionIds.toArray(),",");
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setKey("o.destinationId");
            queryCondition.setOper("in");
            queryCondition.setValue(ids);
            queryBean.getQueryList().add(queryCondition);
        }

//        // 当前管理员是否隶属采购部 并管理指定用户
//        if(!StringUtils.isEmpty(shiroUser.getControlUsers())
//                && wmsProperties.getPurchase().getDeptId().equals(shiroUser.getDeptId())
//        ) {
//            // 绑定指定用户链
//            bindControlQuery(queryBean, shiroUser, "o.salesmanId", false);
//        }

        PageParam<OrderInfo> pageParam = queryBean.toPageParam();
        IPage<OrderInfo> page = currentMapper.page(pageParam.getPage(), pageParam.getEntityWrapper());
        return ResponseBean.success(page);
    }

    @RequestMapping(value = "/log/{id}")
    public ResponseBean log(@PathVariable long id){
        return ResponseBean.success(currentService.logs(id));
    }

    /**
     * 收货信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/consignee/{id}")
    public ResponseBean consignee(@PathVariable long id){
        return ResponseBean.success(currentService.getOrderProcess(id, SupOrderAction.ECEIVING));
    }

    /**
     * 收货信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/payment/{id}")
    public ResponseBean payment(@PathVariable long id){
        return ResponseBean.success(currentService.getOrderProcess(id, SupOrderAction.PAYING));
    }

    @RequiresPermissions(value = "m5254")
    @RequestMapping(value = "/findInfo/{id}", method = RequestMethod.GET)
    public ResponseBean findInfo(@PathVariable Long id,
                                 @SessionAttribute ShiroUser shiroUser) {
        OrderInfo model;
        if (id == 0) {
            model = new OrderInfo();
        } else {
            model = currentService.findFullById(id);
        }
        return ResponseBean.success(model);
    }

    @RequiresPermissions(value = {"m5251", "m5253"}, logical = Logical.OR)
    @RequestMapping(value = "/save", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean save(@RequestBody OrderInfo form, @SessionAttribute ShiroUser shiroUser) throws Exception {
        OrderInfo model = null;
        if (form.getId() != null) {
            // 禁止修改项 做空处理
            model = currentService.update(form,shiroUser);
        }else{
            model = currentService.add(form,shiroUser);
        }

        return ResponseBean.success(model);
    }

    @RequiresPermissions(value = {"m5255", "m5256"}, logical = Logical.OR)
    @RequestMapping(value = "/update-location")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateLocation(@RequestBody OrderLocation form, @SessionAttribute ShiroUser shiroUser) throws Exception {
        if (!currentService.updateLoaction(form)) {
            return ResponseBean.error("保存失败!");
        }
        return ResponseBean.success();
    }

    /**
     * 订单驳回
     */
    @RequiresPermissions("m5257")
    @RequestMapping(value = "/reject", produces = "application/json;charset=UTF-8")
    public ResponseBean reject(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        // 实例化kafka消息体
        KafkaMessage kafkaMessage =new KafkaMessage();
        currentService.reject(kafkaMessage,request,shiroUser);
        if(kafkaMessage.getMessages().size()>0){
            // 发送kafka消息
            kafkaMessage.getMessages().forEach(o->kafkaTemplate.send(o.getTopic(),o.getKey(),o.getMessage()));
        }
        return ResponseBean.success();
    }

    @RequiresPermissions("m5258")
    @RequestMapping(value = "/checking", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean checking(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        ResponseBean res = licensePlateService.discern(1,request.getParams().get("license").toString());
        if(res.getCode()==200){
            request.getParams().put("license",res.getData().toString());
        }else{
            return res;
        }
        currentService.checking(request,shiroUser);
        return ResponseBean.success();
    }

    @RequiresPermissions("m5259")
    @RequestMapping(value = "/eceiving", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean eceiving(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        currentService.eceiving(request,shiroUser);
        return ResponseBean.success();
    }

    @RequiresPermissions("m52591")
    @RequestMapping(value = "/pricing", produces = "application/json;charset=UTF-8")
    public ResponseBean pricing(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        // 实例化kafka消息体
        KafkaMessage kafkaMessage =new KafkaMessage();
        // 处理定价业务
        currentService.pricing(kafkaMessage,request,shiroUser);
        if(kafkaMessage.getMessages().size()>0) {
            // 发送kafka消息
            kafkaMessage.getMessages().forEach(o -> kafkaTemplate.send(o.getTopic(), o.getKey(), o.getMessage()));
        }
        return ResponseBean.success();
    }

    @RequiresPermissions("m52592")
    @RequestMapping(value = "/adjusting", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean adjusting(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        currentService.adjusting(request,shiroUser);
        return ResponseBean.success();
    }

    @RequiresPermissions("m52598")
    @RequestMapping(value = "/replying", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean replying(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        currentService.replying(request,shiroUser);
        return ResponseBean.success();
    }

    @RequiresPermissions("m5281")
    @RequestMapping(value = "/batch/replying", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean batchReplying(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        logger.info("===批量审批===START===");
        List<String> ids = (List<String>) request.getParams().get("ids");
        List<BigDecimal> actualAmounts = (List<BigDecimal>)request.getParams().get("actualAmounts");
        Long supplierId = 0L;
        for (String id : ids) {
            request.setId(Long.valueOf(id));
            request.getParams().put("actualAmount",actualAmounts.get(ids.indexOf(id)));
            currentService.replying(request, shiroUser);
        }
        logger.info("===批量审批===END===");
        return ResponseBean.success();
    }

    @RequiresPermissions("m52593")
    @RequestMapping(value = "/canceling", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean canceling(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        currentService.canceling(request,shiroUser);
        return ResponseBean.success();
    }

    @RequiresPermissions("m52594")
    @RequestMapping(value = "/returning", produces = "application/json;charset=UTF-8")
    public ResponseBean returning(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        // 实例化kafka消息体
        KafkaMessage kafkaMessage =new KafkaMessage();
        // 处理定价业务
        Long returnId = currentService.returning(kafkaMessage,request,shiroUser);
        if(kafkaMessage.getMessages().size()>0) {
            // 发送kafka消息
            kafkaMessage.getMessages().forEach(o -> kafkaTemplate.send(o.getTopic(), o.getKey(), o.getMessage()));
        }
        return ResponseBean.success(returnId);
    }

    @RequiresPermissions("m52595")
    @RequestMapping(value = "/paying", produces = "application/json;charset=UTF-8")
    public ResponseBean paying(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        // 实例化kafka消息体
        KafkaMessage kafkaMessage =new KafkaMessage();
        // 处理定价业务
        currentService.paying(kafkaMessage,request,shiroUser);
        if(kafkaMessage.getMessages().size()>0) {
            // 发送kafka消息
            kafkaMessage.getMessages().forEach(o -> kafkaTemplate.send(o.getTopic(), o.getKey(), o.getMessage()));
        }
        return ResponseBean.success();
    }

    @RequiresPermissions("m5291")
    @RequestMapping(value = "/batch/paying", produces = "application/json;charset=UTF-8")
    public ResponseBean bacthPaying(@RequestBody OrderActionRequest request, @SessionAttribute ShiroUser shiroUser) throws Exception {
        // 实例化kafka消息体
        KafkaMessage kafkaMessage =new KafkaMessage();
        List<String> ids = (List<String>) request.getParams().get("ids");
        List<BigDecimal> actualAmounts = (List<BigDecimal>)request.getParams().get("actualAmounts");
        List<BigDecimal> paymentAmounts = (List<BigDecimal>)request.getParams().get("paymentAmounts");
        Long supplierId = 0L;
        for (String id : ids) {
            request.setId(Long.valueOf(id));
            request.getParams().put("actualAmount",actualAmounts.get(ids.indexOf(id)));
            request.getParams().put("paymentAmount",actualAmounts.get(ids.indexOf(id)));
            // 处理定价业务
            currentService.paying(kafkaMessage,request,shiroUser);
        }
        if(kafkaMessage.getMessages().size()>0) {
            // 发送kafka消息
            kafkaMessage.getMessages().forEach(o -> kafkaTemplate.send(o.getTopic(), o.getKey(), o.getMessage()));
        }
        return ResponseBean.success();
    }

    @RequiresPermissions(value = "m52596")
    @RequestMapping(value = "/notification/{id}", method = RequestMethod.GET)
    public ResponseBean notification(@PathVariable Long id,
                                 @SessionAttribute ShiroUser shiroUser) {
        OrderInfo model = currentService.findFullById(id);
        kafkaTemplate.send(KafkaTopic.PUR_ORDER_NOTIFICATION,model.getId().toString(), JSON.toJSONString(model));
        return ResponseBean.success();
    }

    @RequiresPermissions(value = "m52597")
    @RequestMapping(value = "/recycle/{id}", method = RequestMethod.GET)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean recycle(@PathVariable Long id,
                                     @SessionAttribute ShiroUser shiroUser) throws Exception {
        currentService.recycle(id,shiroUser);
        return ResponseBean.success();
    }

    @RequiresPermissions(value = "m5252")
    @RequestMapping("/del")
    public ResponseBean del(@RequestParam(value = "nos") List<Long> ids) {
        ids.forEach(id -> {
            currentService.removeById(id);
        });
        return ResponseBean.success();
    }
}
